package com.ex02.ylw;

import com.util.Resource;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * 加载Servlet类并调用service方法
 *
 * 这就是传说中的servlet容器
 * Created by yangliwei on 2017/7/21.
 */
public class ServletProcess {
    public void process(Request request, Response response) throws ServletException, IOException {
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        URLClassLoader loader = null;

        try {
            URL[] urls = new URL[1];
            //处理协议用的，在new URL对象的时候会自动识别的
            URLStreamHandler streamHandler = null;
            File classPath = new File(Resource.SERVLET_RESOURCE.getProperty());
            //获取该该url仓库，就是放置所有Servlet的地方，这里使用一个类加载器，直接加载所有Servlet
            String repository = new URL("file", null, classPath.getCanonicalPath() + File.separator).toString();
            urls[0] = new URL(null, repository, streamHandler);
            loader = new URLClassLoader(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Class myClass = null;
        try {
            myClass = loader.loadClass(servletName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Servlet servlet = null;

        try {
            servlet = (Servlet) myClass.newInstance();
            //这里使用封装的request和response,
            // 这样就不会在servlet里面暴露了原生的request和response部分方法
            //即request里面的parse方法和response里面的sendStaticResource方法
            // servlet.service(request,response);
            RequestWrapper requestWrapper = new RequestWrapper(request);
            ResponseWrapper responseWrapper = new ResponseWrapper(response);
            servlet.service(requestWrapper,responseWrapper);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}
